package cn.fxyz.web.controller;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import cn.fxyz.entity.User;
import cn.fxyz.service.UserService;

@Controller
public class UserController {
	
	@Resource
	private UserService userService;
	//登录
	@RequestMapping("login")
	public @ResponseBody String Login(User user,HttpServletRequest request) {
		User findUser = userService.findByUser(user);
		System.out.println(findUser);
		if(findUser != null) {
			System.out.println(111);
			if(findUser.getState() == "0") {
				return "active";
			}
			else if(findUser != null) {
				HttpSession session = request.getSession();
				session.setAttribute("user", findUser);
				if(session.getAttribute("cart") != null) {
					return "clientCart";
				}
				return "success";
			}
		} 
		return "no";

	}
	//异步验证账号是否存在
	@RequestMapping("findUserByUsername")
	public @ResponseBody String findUserByUsername(User user,HttpServletRequest request) {
		User findUser = userService.findUserByUsername(user);
		if(findUser != null) {
			return "success";
		}
		return "null";
	}
	//注册
	@RequestMapping("reg")
	public String reg(User user,Model model) {
		user.setJurisdiction("普通用户");
		userService.add(user);
		String msg = "注册成功！请登录邮箱激活！";
		model.addAttribute("msg", msg);
		return "login/msg";
	}
	//注册用户激活
	@RequestMapping("active")
	public String active(User user,Model model) {
		// 根据激活码查询用户:
		User existUser = userService.findByCode(user.getCode());
		String msg = "";
		System.out.println(111);
		// 判断
		if (existUser == null) {
			// 激活码错误的
			msg = "激活失败:激活码错误!";
			model.addAttribute("msg", msg);
		} else {
			// 激活成功
			// 修改用户的状态
			msg = "激活成功！请前往登录页面登录";
			existUser.setState("1");
			existUser.setCode(null);
			System.out.println(444);
			System.out.println(existUser.toString());
			userService.modify(existUser);
			System.out.println(333);
			model.addAttribute("msg", msg);
		}
		System.out.println(222);
		return "login/msg";
	}
	//通过id查找用户，并刷新session中的用户
	@RequestMapping(value="refresh",method=RequestMethod.POST)
	public String refresh(HttpServletRequest request){
		HttpSession session  = request.getSession();
		if(session.getAttribute("user")!=null){
			User user = userService.findById(((User)session.getAttribute("user")).getId());
			session.removeAttribute("user");
			session.setAttribute("user", user);
			return "ok";
		}else{
			return "fail";
		}
	}
	public UserService getUserService() {
		return userService;
	}
	public void setUserService(UserService userService) {
		this.userService = userService;
	}
	
	
}
